<template>
  <div>
    <van-cell-group>
      <van-cell
        v-for="(item,index) in list"
        icon="search"
        :key="index"
        @click="search(item)"
      >
        <div
          slot="title"
          v-html="show(item)"
        ></div>
      </van-cell>
    </van-cell-group>
  </div>
</template>
<script>
import { getSuggestion } from '@/api/search.js'
import { debounce } from 'lodash'
export default {
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      list: []
    }
  },
  watch: {
    searchText: {
      handler: debounce(async function (value) {
        try {
          const { data: res } = await getSuggestion(value)
          this.list = res.data.options
        } catch (err) {
          this.$toast('获取建议失败')
        }
      }, 500),
      immediate: true
    }
  },
  methods: {
    show (value) {
      const text = value
      const reg = new RegExp(this.searchText, 'gi')
      return text.replace(reg, `<span class="active">${this.searchText}</span>`)
    },
    search (text) {
      this.$emit('search', text)
    }
  }
}
</script>
<style lang="less" scoped>
.van-icon-search::before {
  color: #c9c9c9;
}
/deep/ .van-cell .active {
  color: red !important;
}
</style>
